<template>
  <AddOrEditDialog
    ref="addOrEditDialogRef"
    :form="form"
    title="账户"
    :formHeader="formHeader"
    :url="$urls.API_URL_BACKSTAGE_USER_MANAGE"
    :action="action"
    @beforeSubmit="beforeSubmit"
    @afterSubmitSuccess="afterSubmitSuccess"
  >
    <template #departmentId>
      <SysDepartmentTreeSelect
        v-model="form.departmentId"
        clearable/>
    </template>
    <template #roleIds>
      <!--角色列表-->
      <el-checkbox-group v-model="form.roleIds">
        <el-checkbox
          v-for="item in roles"
          :label="item.id"
          :key="item.id"
        >{{item.nameZh}}</el-checkbox>
      </el-checkbox-group>
    </template>
    <!--    <template #name>
          <el-input
            v-model="roleForm['name']"
            clearable/>
        </template>-->
  </AddOrEditDialog>
</template>

<script lang="ts" setup>
import AddOrEditDialog from '@/components/base/table/form/AddOrEditDialog.vue';
import SysDepartmentTreeSelect from '@/components/uem/SysDepartmentTreeSelect.vue';

import {
  computed,
  defineExpose, defineProps, getCurrentInstance, nextTick, onMounted, reactive, ref, withDefaults,
} from 'vue';
import { TableColumn, FormHeader } from '@/types/interface/base_interface';
import {
  Option, userSexDict, userStatusDict, yesOrNoDict,
} from '@/api/dict';
import { Department, Role, User } from '@/types/interface/auth_interface';

const { proxy } = getCurrentInstance();
// 接收父容器参数
interface Props {
  action?: string, // 表单的处理类型，post表示提交，put表示编辑
}
const props = withDefaults(defineProps<Props>(), {
  action: 'post',
});

// 表单元素
const formHeader = ref<FormHeader[]>([
  {
    label: '部门',
    prop: 'departmentId',
    type: 'custom',
    rules: [
      {
        required: true,
        message: '不能为空',
        trigger: 'blur',
      },
    ],
  },
  {
    label: '账户名',
    prop: 'username',
    rules: [
      {
        required: true,
        message: '不能为空',
        trigger: 'blur',
      },
      {
        min: 4,
        max: 20,
        message: '长度在 4 到 20个字符',
        trigger: 'blur',
      },
    ],
  },
  {
    label: '昵称',
    prop: 'nickName',
    rules: [
      {
        required: true,
        message: '不能为空',
        trigger: 'blur',
      },
      {
        min: 2,
        max: 20,
        message: '长度在 2 到 20个字符',
        trigger: 'blur',
      },
    ],
  },
  {
    label: '性别',
    prop: 'sex',
    type: 'select',
    dict: userSexDict,
  },
  {
    label: '账户状态',
    prop: 'status',
    type: 'select',
    dict: userStatusDict,
  },
  {
    label: '描述',
    prop: 'description',
    placeholder: '请输入账户的描述',
    type: 'textarea',
  },
  {
    label: '角色',
    prop: 'roleIds',
    type: 'custom',
    rules: [
      {
        type: 'array', required: true, message: '请至少选择一个角色', trigger: 'change',
      },
    ],
  },
]);
// 读取角色列表
const roles = ref<Role[]>([]);// 定义角色列表
const getRoles = async () => {
  const resData:any = await new proxy.$Request(proxy.$urls.API_URL_BACKSTAGE_ROLE_MANAGE_ALL).get();
  if (resData.success) {
    roles.value = resData.data;
  }
};
onMounted(getRoles);

// 表单对象
const form = ref<User>();
let formInit:User; // 记录表单第一次传入的值,用于表单重置恢复初始值使用
const addOrEditDialogRef = ref(); // 表单ref对象
// 打开对话框，gong供父组件调用，传入表单对象
const openDialog = (user: User) => {
  form.value = { ...user };
  // 角色处理
  if (form.value.roleIds) {
    form.value.roleIds.splice(0);
  } else {
    form.value.roleIds = []; // 定义角色集合
  }
  if (props.action === 'post') { // 如果是添加账户
    roles.value.forEach((role:Role) => {
      if (role.defaultRole === true) { // 如果是默认角色
        (form.value!.roleIds as number[]).push(role.id);// 让复选框开始就选择默认角色
      }
    });
  } else { // 如果是编辑账户
    form.value.roles!.forEach((role:Role) => {
      form.value!.roleIds!.push(role.id);// 让复选框开始就选择该账户已经拥有的角色
    });
    // 获取该账户当前所属部门
    if (form.value.department) {
      form.value.departmentId = form.value.department.id;
    }
  }
  formInit = { ...form.value }; // 获取初始值，用于表单重置。这里要做深拷贝，避免与form对象引用的地址一致，导致无法恢复初始值
  addOrEditDialogRef.value!.openDialog();
};
// 提交表单成功后的钩子函数
const afterSubmitSuccess = () => {
  // 让表单恢复为传入对象时的初始值，注意要深度拷贝，避免初始值收到污染
  form.value = { ...formInit };
};
const beforeSubmit = () => { // 钩子函数，提交表单前的操作
  form.value!.department = { // 创建部门对象
    id: form.value!.departmentId as number,
  };
  console.log(form.value);
};
// 暴露组件给父容器使用
defineExpose({
  openDialog,
});
</script>

<style lang="scss" scoped>

</style>
